<?php

require_once 'Zend/View/Helper/Abstract.php';

class Core_View_Helper_General_RenderImage extends Zend_View_Helper_Abstract
{
    /**
     * comments
     */
    public function renderImage($src, $height = '', $width = '', $attribs = array('class' => 'icon'))
    {
        $absPath = BASE_PATH . '/' . $src;
        $validator = new Zend_Validate_File_Extension(array('jpg', 'jpeg', 'gif', 'png'));
        if (!is_file($absPath) || !$validator->isValid($src)) {
            return '<span>' . $src . '</span>';
        }

        if ($src != '' && is_file($absPath)) {
            $imageSize = getimagesize($absPath);
            $srcHeight = $imageSize[0];
            $srcWidth = $imageSize[1];

            $percentage = 1.0;
            //if the height is greater than the width then adjust by the height
            //otherwise adjust by the width
            if ((isset($height) && !empty($height)) && $srcHeight > $srcWidth) {
                $percentage = $height / $srcHeight;
            } elseif ((isset($width) && !empty($width))) {
                $percentage = $width / $srcWidth;
            }

            if (isset($height) && !empty($height)) {
                $height = 'height:' . round($srcHeight * $percentage) . 'px; ';
            } else {
                $height = '';
            }
            if (isset($width) && !empty($width)) {
                //gets the new value and applies the percentage, then rounds the value
                $width = 'width:' . round($srcWidth * $percentage) . 'px; ';
            } else {
                $width = '';
            }

            $attributes = null;
            if (is_array($attribs)) {
                foreach ($attribs as $k => $v) {
                    $attributes .= $k . "='" . $v . "' ";
                }
            }
            return '<img style="' . $width . $height . '" src="' . $this->view->getBaseUrl() . '/' . $src . '" ' . $attributes . ' />';
        }
    }
}